package com.tre.jdevtemplateboot.web.controller;

import com.tre.jdevtemplateboot.common.constant.SysConstantToken;
import com.tre.jdevtemplateboot.common.dto.PropertiesConfig;
import com.tre.jdevtemplateboot.common.dto.ResponseResult;
import com.tre.jdevtemplateboot.common.enums.AuthenticateTypeEnums;
import com.tre.jdevtemplateboot.common.jwt.IJwtTokenManagerService;
import com.tre.jdevtemplateboot.common.redis.IDataBaseAuthorizationService;
import com.tre.jdevtemplateboot.common.redis.IRedisTokenManagerService;
import com.tre.jdevtemplateboot.common.util.BasedDesUtils;
import com.tre.jdevtemplateboot.exception.business.SysInvalidUserException;
import com.tre.jdevtemplateboot.exception.business.SysRequestTokenCategoryException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;

/**
 * @author JDev
 */
@RestController
@RequestMapping("/user")
public class LoginController {

    @Autowired
    private IRedisTokenManagerService tokenManagerService;
    @Autowired
    private IJwtTokenManagerService jwtTokenManagerService;
    @Autowired
    private PropertiesConfig propertiesVO;
    @Autowired(required = false)
    private IDataBaseAuthorizationService dataBaseAuthorizationService;

    /**
     * Token 签发
     *
     * @param userId
     * @param passWord
     * @param response
     * @return
     */
    @PostMapping("/login")
    public ResponseResult loginJwt(@RequestParam(value = "userId") String userId,
                                   @RequestParam(value = "password") String passWord,
                                   HttpServletResponse response) {
        if (!AuthenticateTypeEnums.JWT.toString().equalsIgnoreCase(propertiesVO.getTokenCategory())) {
            throw new SysRequestTokenCategoryException();
        }
        if (!StringUtils.hasLength(userId) || !StringUtils.hasLength(passWord)) {//验证 用户名 和 密码 都不为空
            throw new SysInvalidUserException();
        }
        dataBaseAuthorizationService.checkLoginFromDbUserInfo(userId, passWord);
        String encoderUserId = BasedDesUtils.encryptBasedDes(userId);
        String resultToken = jwtTokenManagerService.generateToken(encoderUserId);
        response.setHeader(propertiesVO.getPreUserIssuer() + SysConstantToken.SUFFIX_USER_ISSUER, resultToken);
        return ResponseResult.buildOK(encoderUserId);
    }

    /**
     * Token签发，基于Redis存储也校验
     *
     * @param userId
     * @param passWord
     * @param response
     * @return
     */
    @PostMapping("/login/token")
    public ResponseResult login(@RequestParam(value = "userId") String userId,
                                @RequestParam(value = "password") String passWord,
                                HttpServletResponse response) {
        if (!AuthenticateTypeEnums.REDIS.toString().equalsIgnoreCase(propertiesVO.getTokenCategory())) {
            throw new SysRequestTokenCategoryException();
        }
        if (!StringUtils.hasLength(userId) || !StringUtils.hasLength(passWord)) {
            throw new SysInvalidUserException();
        }
        dataBaseAuthorizationService.checkLoginFromDbUserInfo(userId, passWord);
        String encoderUserId = BasedDesUtils.encryptBasedDes(userId);
        String resultToken = tokenManagerService.generateToken(encoderUserId);
        response.setHeader(propertiesVO.getPreUserIssuer() + SysConstantToken.SUFFIX_USER_ISSUER, resultToken);
        return ResponseResult.buildOK(encoderUserId);
    }
}
